import axios from 'axios'
import qs from 'qs'

const axionInstance = axios.create({
  baseURL:'',
  timeout:10000,


  transformRequest: [function(data, headers) {
    if (headers['Content-Type'].indexOf('application/x-www-form-urlencoded') !== -1) {
      if (data) {
        return qs.stringify(data)
      }
    }
    if (headers['Content-Type'].indexOf('multipart/form-data') !== -1) {
      if (data) {
        const formData = new FormData()
        for (const i in data) {
          if (data[i]) {
            formData.append(i, data[i])
          }
        }
        return formData
      }
    }
    return data
  }],
  // headers: { 'Content-Type': 'multipart/form-data' } // 注意 Content-Type首字母大写，不然上传文件时不生成boundary 随机数 导致后台报no multipart boundary was found
  headers: { 'Content-Type': 'application/json' }


})

axionInstance.interceptors.request.use(data=>data,err=>{
  console.log(err)
})

axionInstance.interceptors.response.use(data=>{
  console.log(data)
  if(data.status === 200){
    return data.data
  }
  return data
},err=>{
  if (err.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    // console.log(err.response.data);
    // console.log(err.response.status);
    // console.log(err.response.headers);
    return err.response.data
  } else {
    // Something happened in setting up the request that triggered an Error
    console.log('Error', err.message);
    return {code:500,msg:err.message}
  }

})

const requestGet = (url,params,config)=>{
  return axionInstance.get(url,{
    params,
    ...config
  })
}

const requestPost = (url,data,config)=>{
  return axionInstance.post(url,data,config)
}

export default axionInstance

export {
  requestGet,
  requestPost
}